package com.xzlf.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.xzlf.job.QuartzJob1;
import org.quartz.*;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.sql.DataSource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
public class QuartzConfig {

    @Bean
    @QuartzDataSource
    @ConfigurationProperties(prefix = "spring.quartz.properties.org.quartz.datasource")
    public DataSource quartzDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public JobDetail jobDetail() {
        return JobBuilder.newJob().ofType(QuartzJob1.class)
                .storeDurably()
                .withIdentity("Qrtz_Job_Detail")
                .withDescription("Invoke Sample Job service...")
                .build();
    }


    @Bean
    public JobDetail jobDetail2() {
        QuartzJobBean quartzJobBean2 = new QuartzJobBean() {
            @Override
            protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println("内部类方式创建job：" + simpleDateFormat.format(new Date()));
            }
        };
        return JobBuilder.newJob(quartzJobBean2.getClass()).storeDurably().build();
    }

    /**
     * 触发器，代表一个调度参数的配置,什么时候去调度
     *
     * @return
     */
    @Bean
    public Trigger trigger(JobDetail jobDetail) {
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity("Qrtz_Trigger")
                .withDescription("SIMple trigger")
                .withSchedule(SimpleScheduleBuilder.repeatHourlyForever().withIntervalInSeconds(2))
                .build();

    }

    @Bean
    public Trigger trigger2(JobDetail jobDetail2) {
        SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder
                .simpleSchedule()
                .withIntervalInSeconds(2)
                .repeatForever();
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail2)
                .withSchedule(simpleScheduleBuilder)
                .build();
    }


}
